<template>
  <div class="history-trend">
    <BasicTitle title="实时数据趋势分析"></BasicTitle>
    <div class="detail-chart">
      <div class="btn-container">
        <el-button type="success" text @click="shangXiaYeClcik(1)">
          <img :src="leftArrow" alt="" />
          上一页
        </el-button>
        <el-button type="success" text @click="shangXiaYeClcik(2)">
          下一页
          <img :src="rightArrow" alt="" />
        </el-button>
      </div>
      <div
        v-if="istitle"
        style="
          position: absolute;
          height: 400px;
          width: 100%;
          text-align: center;
          margin-top: 100px;
          font-size: 22px;
          font-weight: 600;
        "
      >
        当前参数机台在此时间段无数据展示
      </div>
      <LineChart
        :istitle="istitle"
        :startTime="startTimeVal"
        :endTime="endtimeVal"
        :tuData="tuData"
        :seleCanShus="seleCanShu"
        :seleCanShuBools="seleCanShuBools"
      ></LineChart>
    </div>
  </div>
</template>
<script setup lang="ts">
  import dayjs from 'dayjs'
  import { ElMessage } from 'element-plus'
  import LineChart from './lineChart.vue'
  import leftArrow from '@/assets/images/device-monitor/chevron-left.png'
  import rightArrow from '@/assets/images/device-monitor/chevron-right.png'
  import {
    getWenShiDuLiShiQuShi,
    getliShiShuJuTuCanShuList,
    postGongXuXiaLiShiQuShiTu,
    getQingHuaXiaBaoKuoDeGongXu
  } from '@/api/shengChanJianShi'
  import { getLuoTongZhiJiJiTaiTheGongYi } from '@/api/gongGongChaXun'

  const props = defineProps({
    statusCode: String,
    processName: String
  })

  const istitle = ref(false)
  const shiJianID = ref('8')
  const timeType = ref('datetime')
  const timeVal = ref()
  const startTimeVal = ref(dayjs().format('YYYY-MM-DD HH:mm'))
  const endtimeVal = ref(dayjs().subtract(8, 'hour').format('YYYY-MM-DD HH:mm'))
  const tuData = ref<any>({})
  const seleCanShu = ref<any>([])
  const seleCanShuBools = ref<any>({})
  const jiTaiID = ref()
  const jitaiList = ref<any>([])
  const shuJuList = ref<any>([])
  const wenShiDuList = ref<any>([])
  const canShuList = ref<any>([])
  const canShuIDArr = ref<any>([])
  const gongXuList = ref<any>([])
  const gongXuID = ref()
  // const processName = ref()

  // 获取清花下工序
  const getQingHuaData = () => {
    getQingHuaXiaBaoKuoDeGongXu().then((res: any) => {
      gongXuList.value = res
      gongXuID.value = res[0].id
      // processName.value = res[0].name
      chuShiHuaData()
    })
  }

  const chuShiHuaData = () => {
    Promise.all([getTrendChartParamsList(), getWindingProcessMachineData()]).then(() => {
      initLiShiQuShiTu()
    })
  }

  const initLiShiQuShiTu = () => {
    seleCanShu.value = []
    Promise.all([getProcessTrendChartData(), getHumitureTrendChartData()]).then((res: any) => {
      console.log(res)
      if (shuJuList.value.length === 0) {
        istitle.value = true
        return
      }
      istitle.value = false
      shuJuList.value[0].machineRtValue.sort((a, b) => {
        return Date.parse(a.CreationTime) - Date.parse(b.CreationTime)
      })
      let itemArr = canShuIDArr.value.map((value, index) => {
        let item = canShuList.value.find((value1) => {
          return value1.code === value
        })
        seleCanShu.value.push(item.name)
        seleCanShuBools.value[item.name] = true
        return {
          title: seleCanShu.value[index],
          valueData: shuJuList.value[0].machineRtValue.map((value1) => {
            return [dayjs(value1.CreationTime).format('YYYY-MM-DD HH:mm'), value1[value]]
          })
        }
      })

      let itemArr2: any = []
      wenShiDuList.value.forEach((value) => {
        let arr1: any = []
        let arr2: any = []
        if (value.detail !== null) {
          seleCanShu.value.push(value.name + '温度')
          seleCanShu.value.push(value.name + '湿度')
          seleCanShuBools.value[value.name + '温度'] = false
          seleCanShuBools.value[value.name + '湿度'] = false
          value.detail.forEach((value2) => {
            arr1.push([
              dayjs(value2.timeStamp).format('YYYY-MM-DD HH:mm'),
              parseFloat(value2['temperatureActual']).toFixed(2)
            ])
            arr2.push([
              dayjs(value2.timeStamp).format('YYYY-MM-DD HH:mm'),
              parseFloat(value2['humidityActual']).toFixed(2)
            ])
          })

          itemArr2.push({
            title: value.name + '温度',
            valueData: arr1
          })

          itemArr2.push({
            title: value.name + '湿度',
            valueData: arr2
          })
        }
      })

      tuData.value = {
        canShuShuLiang: itemArr.length,
        canShuData: [...itemArr, ...itemArr2],
        yZhouArr: itemArr
      }
    })
  }

  // 上下页点击事件
  const shangXiaYeClcik = (index) => {
    let jianGe = shiJianID.value === '自定义' ? 24 : shiJianID.value
    if (index === 1) {
      if (timeType.value === 'datetime') {
        startTimeVal.value = endtimeVal.value
        endtimeVal.value = dayjs(endtimeVal.value)
          .subtract(Number(jianGe), 'hour')
          .format('YYYY-MM-DD HH:mm')
        timeVal.value = startTimeVal.value
      } else {
        ;(endtimeVal.value = dayjs(endtimeVal.value)
          .subtract(Number(jianGe), 'hour')
          .format('YYYY-MM-DD HH:mm')),
          (startTimeVal.value = dayjs(startTimeVal.value)
            .subtract(Number(jianGe), 'hour')
            .format('YYYY-MM-DD HH:mm'))
        timeVal.value = [endtimeVal.value, startTimeVal.value]
      }
      initLiShiQuShiTu()
    } else {
      if (timeType.value === 'datetime') {
        endtimeVal.value = startTimeVal.value
        startTimeVal.value = dayjs(startTimeVal.value)
          .add(Number(jianGe), 'hour')
          .format('YYYY-MM-DD HH:mm')
        timeVal.value = startTimeVal.value
      } else {
        ;(endtimeVal.value = dayjs(endtimeVal.value)
          .add(Number(jianGe), 'hour')
          .format('YYYY-MM-DD HH:mm')),
          (startTimeVal.value = dayjs(startTimeVal.value)
            .add(Number(jianGe), 'hour')
            .format('YYYY-MM-DD HH:mm'))
        timeVal.value = [endtimeVal.value, startTimeVal.value]
      }
      initLiShiQuShiTu()
    }
  }

  const getProcessTrendChartData = () => {
    return new Promise<void>((resolve) => {
      // 计算两个时间间隔天数
      const s = Date.parse(endtimeVal.value)
      const e = Date.parse(startTimeVal.value)
      const d = (e - s) / (1000 * 60 * 60 * 24)

      if (d > 1) {
        ElMessage.warning('开始时间和结束时间间隔不能大于一天！')
        return
      }
      let data = {
        firstCraftNodeName: props.processName,
        code: canShuIDArr.value,
        machineDocumentIds: [jiTaiID.value],
        start: endtimeVal.value,
        end: startTimeVal.value
      }
      tuData.value = {}
      postGongXuXiaLiShiQuShiTu(data)
        .then((res: any) => {
          shuJuList.value = res
          resolve(res)
        })
        .catch(() => {
          istitle.value = true
        })
    })
  }

  // 获取温湿度历史趋势图
  const getHumitureTrendChartData = () => {
    return new Promise<void>((resolve) => {
      let data = {
        machineDocumentId: jiTaiID.value,
        begin: endtimeVal.value,
        end: startTimeVal.value
      }
      wenShiDuList.value = []
      getWenShiDuLiShiQuShi(data).then((res: any) => {
        wenShiDuList.value = res
        resolve(res)
      })
    })
  }

  const getTrendChartParamsList = () => {
    return new Promise<void>((resolve) => {
      getliShiShuJuTuCanShuList(props.processName).then((res) => {
        canShuList.value = res
        canShuIDArr.value = [canShuList.value[0].code]
        seleCanShu.value = [canShuList.value[0].name]
        resolve()
      })
    })
  }

  const getWindingProcessMachineData = () => {
    return new Promise<void>((resolve) => {
      getLuoTongZhiJiJiTaiTheGongYi(props.processName).then((res: any) => {
        res.sort((a, b) => {
          return a.machineName.localeCompare(b.machineName, undefined, {
            numeric: true,
            sensitivity: 'base'
          })
        })
        jitaiList.value = res.map((val) => {
          return {
            id: val.id,
            machineName: val.machineName + '-' + val.machineTypeName
          }
        })
        jiTaiID.value = jitaiList.value[0].id
        resolve()
      })
    })
  }

  onMounted(() => {
    timeVal.value = dayjs().format('YYYY-MM-DD HH:mm')
    if (props.statusCode === '111050') {
      // 清花工序 历史趋势图
      getQingHuaData()
    } else {
      chuShiHuaData()
    }
  })
</script>
<style scoped lang="scss">
  .history-trend {
    background-color: #fff;
    padding: 20px;
  }
  .btn-container {
    margin-top: 25px;
    display: flex;
    justify-content: space-between;
  }
</style>
